package com.ap.core.storedprocedure.api;


import com.ap.core.common.tuple.ThreeTuple;
import com.ap.core.common.types.ParameterType;

import java.sql.CallableStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;


/**
 * Utility class for executing stored procedures.
 * 
 */
public class BaseStoredProcedure {
    
    protected StoredProcedureInfo storedProcedureInfo;
    /**
     * Initialises the call string and in parameters.
     * 
     * @param storedProcedureInfo - info object for stored procedure.
     */
    protected BaseStoredProcedure(StoredProcedureInfo storedProcedureInfo) {
        this.storedProcedureInfo = storedProcedureInfo;
    }
    
    protected void setInOutVariables(CallableStatement cs) throws SQLException {
        int index = 0;
        for (ThreeTuple<Integer, ?, ParameterType> inParam : storedProcedureInfo.getInParams()) {
            if(ParameterType.IN == inParam.third){
                cs.setObject(++index, inParam.second, inParam.first);
            }else{
                cs.registerOutParameter(++index, inParam.first);
            }
        }
    }

    /**
     * Closes all the resources.
     * 
     * @param callableStatement Callable statement to close.
     * @param resultSets Resultset to close.
     */
    protected void closeResources( CallableStatement callableStatement, List<ResultSet> resultSets) {
        
        try {
            if (resultSets != null) {
                for(ResultSet resultSet : resultSets){
                    resultSet.close();
                }
            }
        } catch (SQLException e) {
            throw new AssertionError(e);
        } finally {
            try {
                if (callableStatement != null) {
                    callableStatement.close();
                }
            } catch (SQLException e) {
                throw new AssertionError(e);
            }
        }
        
    }

}
